using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Xeml.Document;
using Mpi.Common.Collections;
using Xeml.Document.Contracts;

namespace Xid.Controls
{
    public partial class SsC_ObservationControl : UserControl
    {

        private SsC_GermPlasmCtrl creatorCtrl;

        public SsC_GermPlasmCtrl CreatorCtrl
        {
            get { return creatorCtrl; }
            set { creatorCtrl = value; }
        }

        private int poolSize = 1;

        public int PoolSize
        {
            get { return poolSize; }
            set { poolSize = value; }
        }

        private Observation obs;

        public Observation ObservationPrototype
        {
            get { return obs; }
            
        }

        //private PartitionCollection parts;

        //public PartitionCollection Parts
        //{
        //    get { return parts; }
        //    set { parts = value; }
        //}

        private SsC_SampleCtrl sampleCtrl;

        public SsC_SampleCtrl SampleCtrl
        {
            get { return sampleCtrl; }
            set { sampleCtrl = value; }
        }


        private List<SsC_PartitionCtrl> partCtrls;

        public List<SsC_PartitionCtrl> PartitionCtrls
        {
            get { return partCtrls; }
         
        }


        public SsC_ObservationControl()
        {
            InitializeComponent();
            this.partCtrls = new List<SsC_PartitionCtrl>();
            this.obs = new Observation();
            this.obs.Destructive = true;
            this.obs.Duration = TimeSpan.FromSeconds(5);
            checkBoxDestructive.DataBindings.Add("Checked", obs, "Destructive",true, DataSourceUpdateMode.OnPropertyChanged);
            timeSpanBox1.DataBindings.Add("Value", obs, "Duration", true, DataSourceUpdateMode.OnPropertyChanged);

             
            this.numericUpDown1.DataBindings.Add("Value", this, "PoolSize", true, DataSourceUpdateMode.OnPropertyChanged);

            textBoxTerm.PreviewKeyDown += new PreviewKeyDownEventHandler(textBoxTerm_PreviewKeyDown);
            
        }

        void textBoxTerm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddTermToList();
            }
        }


        private IDocument _xemlDoc;
        public void Populate(IDocument doc)
        {
            _xemlDoc = doc;
            comboBoxOntologyAlias.SelectedValueChanged +=new EventHandler(comboBoxOntologyAlias_SelectedValueChanged);
            comboBoxOntologyAlias.DataSource = _xemlDoc.DocumentResources.DevelopmentalOntologyHandler;
            comboBoxOntologyAlias.DisplayMember = "NameSpaceAlias";

        }

        private List<IOntologyTerm> _currentTerms = new List<IOntologyTerm>();
        void comboBoxOntologyAlias_SelectedValueChanged(object sender, EventArgs e)
        {
            OntologyHandlerResource ohr = comboBoxOntologyAlias.SelectedValue as OntologyHandlerResource;
            if (ohr != null && ohr.ComponentState == ComponentLoadState.Loaded)
            {
                if (ohr.Handler.OntologyLoadState != OntologyLoadState.Loaded)
                {
                    ohr.LoadOntology();
                }
                if (ohr.Handler.OntologyLoadState == OntologyLoadState.Loaded)
                {

                    //comboBoxTerm.DataSource = (ohr.Handler as IOrganismStructureOntologyHandler).Supervisors;
                    //comboBoxTerm.DisplayMember = "Name";

                    _currentTerms.Clear();
                    textBoxTerm.AutoCompleteCustomSource.Clear();
                    foreach (IOntologyTerm isup in (ohr.Handler as IPlainOntologyHandler).Terms)
                    {
                        _currentTerms.Add(isup);
                    }

                    string[] terms = new string[_currentTerms.Count];
                    for (int i = 0; i < terms.Length; i++)
                    {
                        terms[i] = _currentTerms[i].Prototype.Name;
                    }

                    textBoxTerm.AutoCompleteCustomSource.AddRange(terms);
                }
                else
                {
                }
            }
            else
            {

            }
        }

        private void AddTermToList()
        {

            IOntologyTerm sup = _currentTerms.Find(delegate(IOntologyTerm x) { return x.Prototype.Name == textBoxTerm.Text; });
            if (sup != null)
            {
                // IMaterialSupervisor sup = _currentTerms[textBoxTerm.Text];

                if (!obs.DevelopmentalStages.Contains(sup.TermId))
                {
                    Term m = sup.EmitDefaultObject(true);
                    obs.DevelopmentalStages.Add(m);
                    ListViewItem lvi = new ListViewItem(m.Name);
                    lvi.Tag = m;
                    lvi.ToolTipText = sup.Definition;

                    listView1.Items.Add(lvi);
                    textBoxTerm.Text = "";
                }

            }
        }

        private void RemoveTerm()
        {
            foreach (ListViewItem lvi in listView1.SelectedItems)
            {
                obs.DevelopmentalStages.Remove(lvi.Tag as Term);
                listView1.Items.Remove(lvi);
            }
        }
 

        //void OnPartitionRemoved(object sender, Mpi.Common.Collections.ItemEventArgs<Partition> e)
        //{
        //    if (PartitionRemoved != null)
        //        this.PartitionRemoved(this, e);
        //}

        //void OnPartitionAdded(object sender, Mpi.Common.Collections.ItemEventArgs<Partition> e)
        //{
        //    if (PartitionAdded != null)
        //        this.PartitionAdded(this, e);
        //}


        public event EventHandler<PartitionControlEventArgs> PartitionCtrlAdded;
        public event EventHandler<PartitionControlEventArgs> PartitionCtrlRemoved;

        private void kryptonButtonAddObservation_Click(object sender, EventArgs e)
        {
            SsC_PartitionCtrl pc = new SsC_PartitionCtrl();
            this.partCtrls.Add(pc);
            this.ObservationPrototype.Partitions.Add(pc.Partition);

            if(PartitionCtrlAdded != null)
                PartitionCtrlAdded(this,new PartitionControlEventArgs(pc));

        }

        private void kryptonButtonRemoveObservation_Click(object sender, EventArgs e)
        {

            if (this.partCtrls.Count > 0)
            {
                SsC_PartitionCtrl pc = this.partCtrls[this.partCtrls.Count - 1];
                this.ObservationPrototype.Partitions.Remove(pc.Partition);
                this.partCtrls.RemoveAt(this.partCtrls.Count - 1);
                if (PartitionCtrlRemoved != null)
                    PartitionCtrlRemoved(this, new PartitionControlEventArgs(pc));
            }
        }


        public class PartitionControlEventArgs : EventArgs
        {
            private SsC_PartitionCtrl control;
            public SsC_PartitionCtrl Control
            {
                get { return control; }
            }

            public PartitionControlEventArgs(SsC_PartitionCtrl c)
            {
                this.control = c;
            }

        }

        private void kryptonButton1_Click(object sender, EventArgs e)
        {
            AddTermToList();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RemoveTerm();
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            deleteToolStripMenuItem.Enabled = listView1.SelectedItems.Count > 0;
        }

        private void listView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Delete && listView1.SelectedItems.Count > 0)
            {
                RemoveTerm();
            }
        }

        private void kryptonButton2_Click(object sender, EventArgs e)
        {
            OntologyHandlerResource ohr = comboBoxOntologyAlias.SelectedValue as OntologyHandlerResource;
            HirachicalViewFrm hvf = new HirachicalViewFrm();
            hvf.Setup(ohr.Handler);
            hvf.ShowDialog();
            if (hvf.ShowDialog() == DialogResult.OK && hvf.SelectedTerm != null)
            {
                textBoxTerm.Text = hvf.SelectedTerm.Prototype.Name;
            }
        }

    }
}
